import axios from 'axios'
import { Notification } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Cookies from 'js-cookie'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  timeout: 1200000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['jwt-token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    const { code, message, data } = response.data
    if (code === 200) return data
    if (code === 401) {
      store.dispatch('LogOut').then(() => {
        // 用户登录界面提示
        Cookies.set('point', 401)
        location.reload()
      })
    } else {
      if (message) {
        Notification.error({
          title: message,
          duration: 5000
        })
      }
    }
    return Promise.reject(response.data)
  },
  error => {
    if (error.toString().indexOf('Error: timeout') !== -1) {
      Notification.error({
        title: '网络请求超时',
        duration: 5000
      })
      return Promise.reject(error)
    }
    return Promise.reject(error)
  }
)
export default service
